# Title     : TODO
# Objective : TODO
# Created by: Administrator
# Created on: 2019/7/24

library(ggrepel)
library(ropls)
library(pROC)
library(egg)
library(randomForest)
library(Boruta)
library(magrittr)
library(optparse)
library(caret)
library(tidyverse)

createWhenNoExist <- function(f) {
  !dir.exists(f) && dir.create(f)
}

option_list <- list(
  make_option("--i", default = "AllMet.csv", type = "character", help = "metabolite data file"),
  make_option("--g", default = "SampleInfo.csv", type = "character", help = "sample group file"),
  make_option("--base", default = "metabo_base.R", type = "character", help = "metabo base R file")
)
opt <- parse_args(OptionParser(option_list = option_list))

options(digits = 3)
source(opt$base)

sampleInfo <- read.csv(opt$g, header = T, stringsAsFactors = F) %>%
  select(c("SampleID", "ClassNote"))

head(sampleInfo)

parent <- paste0("./")
createWhenNoExist(parent)

diffNames <- getDiffNames()

orignalData <- read.csv(opt$i, header = T, stringsAsFactors = F) %>%
  select(-c("HMDB", "KEGG", "Class")) %>%
  filter(Metabolite %in% diffNames) %>%
  gather("SampleID", "Value", -Metabolite) %>%
  spread(Metabolite, "Value") %>%
  inner_join(sampleInfo, by = c("SampleID"))

data <- orignalData %>%
  mutate(ClassNote = factor(ClassNote, levels = unique(ClassNote))) %>%
  as.data.frame() %>%
  column_to_rownames("SampleID")

glmRs <- glm(ClassNote ~ ., data = data, family = binomial(link = "logit"))
varImp <- varImp(glmRs, scale = T)

varImp

varImpDf <- varImp %>%
  rownames_to_column("Metabolite") %>%
  rename(VarImp = Overall) %>%
  arrange(desc(VarImp)) %>%
  mutate(Metabolite = str_replace_all(Metabolite, "`", ""))

varImpDf

write.csv(varImpDf, "LR_VarImp.csv", row.names = F)

Yhat <- fitted(glmRs)

YDf <- Yhat %>%
  as.data.frame() %>%
  rownames_to_column("SampleID") %>%
  set_colnames(c("SampleID", "Value"))

YDf

thresh = 0.5
uniq.group <- unique(orignalData$ClassNote)
Yfac <- as.factor(orignalData$ClassNote)
YhatFac <- cut(Yhat, breaks = c(-Inf, thresh, Inf), labels = c(uniq.group[1], uniq.group[2]))
sum <- length(YhatFac)
count <- 0

for (i in 1:length(YhatFac)) {
  if (as.character(YhatFac[i]) == as.character(Yfac[i])) {
    count = count + 1
  }
}
if (count / sum < 0.5) {
  YhatFac = cut(Yhat, breaks = c(-Inf, thresh, Inf), labels = c(uniq.group[2], uniq.group[1]))
}
cTab = table(Yfac, YhatFac)
pre_summary = table(YhatFac, Yfac)

print(pre_summary)
print(pre_summary %>% as.data.frame())
summaryTb <- pre_summary %>%
  as.data.frame() %>%
  as_tibble() %>%
  rename(Var1 = 1, Var2 = 2) %>%
  spread(Var2, "Freq")
print("=log=")
print(summaryTb)
summaryMatrix <- summaryTb %>%
  select(-"Var1") %>%
  as.matrix()
diagSum <- sum(diag(summaryMatrix))
sum <- sum(summaryMatrix)
predictive <- (diagSum / sum) %>%
  round(3)
finalSummaryTb <- summaryTb %>%
  mutate(`Model predictive accuracy` = c(predictive, "")) %>%
  rename(` ` = Var1)
print(finalSummaryTb)

write_csv(finalSummaryTb, "LR_Prediction_Summary.csv")

predictDf1 <- YDf %>%
  mutate(LR_prediction = YhatFac)
predictFinalDf1 <- sampleInfo %>%
  left_join(predictDf1, by = c("SampleID"))
write_tsv(predictFinalDf1, "Classification_Result.txt")

predictDf <- YDf %>%
  mutate(Prediction = YhatFac)
predictFinalDf <- sampleInfo %>%
  left_join(predictDf, by = c("SampleID")) %>%
  rename(Sample = SampleID) %>%
  rename(Probability = Value) %>%
  mutate_at(vars("Probability"), function(x) {
    ifelse(x > 0.5, x, 1 - x)
  }) %>%
  select(-c("Probability"), "Probability")

write_csv(predictFinalDf, "LR_Prediction.csv")